﻿using System;
using System.Security.Cryptography;
using System.Text;

namespace JinJiang.BookingEngine.Services
{
    public class Md5Utils
    {
        private static readonly String[] s_HexDigits = {
                                                           "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"
                                                       };

        public static String EncodeByMd5(string originString)
        {
            if (originString != null)
            {
                try
                {
                    HashAlgorithm algorithm = MD5.Create();
                    var results = algorithm.ComputeHash(Encoding.UTF8.GetBytes(originString));
                    var resultString = ByteArrayToHexString(results);
                    var pass = resultString.ToUpper();
                    return pass;
                }
                catch (Exception ex)
                {
                }
            }
            return null;
        }

        private static String ByteArrayToHexString(byte[] bytes)
        {
            var resultSb = new StringBuilder();
            for (var i = 0; i < bytes.Length; i++)
            {
                resultSb.Append(ByteToHexString(bytes[i]));
            }
            return resultSb.ToString();
        }

        private static String ByteToHexString(byte b)
        {
            int n = b;
            if (n < 0)
            {
                n = 256 + n;
            }
            var d1 = n / 16;
            var d2 = n % 16;
            return s_HexDigits[d1] + s_HexDigits[d2];
        }
    }
}